package id.web.faisalabdillah.xtimesheet.web.ctrl;

import java.util.ArrayList;
import java.util.List;

import id.web.faisalabdillah.xtimesheet.domain.FileStorage;
import id.web.faisalabdillah.xtimesheet.services.IFileStorageService;
import id.web.faisalabdillah.xtimesheet.web.model.FileStorageModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.appengine.api.datastore.Blob;

@Controller
@RequestMapping("/admin/upload")
public class FileUploadCtrl {
	
	@Autowired
	private IFileStorageService fileStorageService;
	
	
	@RequestMapping("/list")
	public String listUpload(){
		return "admin/upload/list";
	}
	
	@RequestMapping("/list/{page}")
	public @ResponseBody List<FileStorage> listPaging(@PathVariable("page") int page){
		System.out.println(page);
		List<FileStorage> list=new ArrayList<FileStorage>();
		FileStorage file = new FileStorage();
		file.setCodename("apalah");
		file.setContentType("ga tau lah");
		file.setDescription("ntah lah");
		return list;
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String showUpload(Model model){
		model.addAttribute(new FileStorageModel());
		return "admin/upload/upload";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String processUpload(FileStorageModel fileStorageModel,BindingResult result){
		if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                    System.err.println("Error: " + error.getCode() + " - "
                                    + error.getDefaultMessage());
            }
            return "admin/upload/upload";
		}
		FileStorage fileStorage=new FileStorage();
		fileStorage.setCodename(fileStorageModel.getCodename());
		fileStorage.setContentType(fileStorageModel.getFile().getContentType());
		fileStorage.setFile_name(fileStorageModel.getFile().getOriginalFilename());
		fileStorage.setFile(new Blob(fileStorageModel.getFile().getBytes()));
		fileStorageService.insert(fileStorage);
		return "admin/upload/upload";
	}
}
